﻿using Artech.Core.Globalization.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Artech.Core.Globalization
{
    public static class DateTimeConverter
    {
        private static bool convertTimeToUtc = GlobalizationSettings.GetSettings().DateTimeKind;
        private static DateTime[] igoredTimes = new DateTime[]
        {
            new DateTime(1753,1,1,0,0,0),
            new DateTime(9998, 12, 31, 0, 0, 0),
            DateTime.MinValue,
            DateTime.MaxValue
        };

        public static DateTime ConvertBeforeWritting(DateTime dateTime)
        {
            if (!convertTimeToUtc || dateTime.Kind == DateTimeKind.Utc || igoredTimes.Any(time => time.Ticks == dateTime.Ticks))
            {
                return dateTime;
            }
            return TimeZoneInfo.ConvertTimeToUtc(dateTime, ApplicationContext.Current.TimeZone);
        }

        public static DateTime ConvertAfterReading(DateTime dateTime)
        {
            if (!convertTimeToUtc || dateTime.Kind == DateTimeKind.Local || igoredTimes.Any(time => time.Ticks == dateTime.Ticks))
            {
                return dateTime;
            }
            return TimeZoneInfo.ConvertTimeFromUtc(dateTime, ApplicationContext.Current.TimeZone);
        }

        public static DateTime Now
        {
            get
            {
                if (convertTimeToUtc)
                {
                    return DateTime.UtcNow;
                }
                return DateTime.Now;
            }
        }
    }
}
